home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / ProgramD2.iso / J A V A / Java Development Kit V1.2 / jdk12-win32(1).exe / data1.cab / demos / demo / jfc / SampleTree / SampleTree.java < prev    next >
Encoding:
Java Source  |  1998-12-01  |  13.1 KB  |  430 lines

  1. /*
  2.  * @(#)SampleTree.java    1.16 98/08/26
  3.  *
  4.  * Copyright 1997, 1998 by Sun Microsystems, Inc.,
  5.  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
  6.  * All rights reserved.
  7.  *
  8.  * This software is the confidential and proprietary information
  9.  * of Sun Microsystems, Inc. ("Confidential Information").  You
  10.  * shall not disclose such Confidential Information and shall use
  11.  * it only in accordance with the terms of the license agreement
  12.  * you entered into with Sun.
  13.  */
  14.  
  15. import javax.swing.*;
  16. import javax.swing.event.*;
  17. import java.awt.BorderLayout;
  18. import java.awt.Color;
  19. import java.awt.Dimension;
  20. import java.awt.FlowLayout;
  21. import java.awt.event.ActionEvent;
  22. import java.awt.event.ActionListener;
  23. import java.awt.event.WindowAdapter;
  24. import java.awt.event.WindowEvent;
  25. import javax.swing.tree.*;
  26.  
  27. /**
  28.   * A demo for illustrating how to do different things with JTree.
  29.   * The data that this displays is rather boring, that is each node will
  30.   * have 7 children that have random names based on the fonts.  Each node
  31.   * is then drawn with that font and in a different color.
  32.   * While the data isn't interesting the example illustrates a number
  33.   * of things:
  34.   *
  35.   * For an example of dynamicaly loading children refer to DynamicTreeNode.
  36.   * For an example of adding/removing/inserting/reloading refer to the inner
  37.   *     classes of this class, AddAction, RemovAction, InsertAction and
  38.   *     ReloadAction.
  39.   * For an example of creating your own cell renderer refer to
  40.   *     SampleTreeCellRenderer.
  41.   * For an example of subclassing JTreeModel for editing refer to
  42.   *     SampleTreeModel.
  43.   *
  44.   * @version 1.16 08/26/98
  45.   * @author Scott Violet
  46.   */
  47.  
  48. public class SampleTree
  49. {
  50.     /** Window for showing Tree. */
  51.     protected JFrame            frame;
  52.     /** Tree used for the example. */
  53.     protected JTree             tree;
  54.     /** Tree model. */
  55.     protected DefaultTreeModel        treeModel;
  56.  
  57.     /**
  58.       * Constructs a new instance of SampleTree.
  59.       */
  60.     public SampleTree() {
  61.     // Force SampleTree to come up in the Cross Platform L&F
  62.     try {
  63.         UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
  64.         // If you want the System L&F instead, comment out the above line and
  65.         // uncomment the following:
  66.         // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  67.     } catch (Exception exc) {
  68.         System.err.println("Error loading L&F: " + exc);
  69.     }
  70.  
  71.  
  72.     JMenuBar         menuBar = constructMenuBar();
  73.     JPanel           panel = new JPanel(true);
  74.  
  75.     frame = new JFrame("SampleTree");
  76.     frame.getContentPane().add("Center", panel);
  77.     frame.setJMenuBar(menuBar);
  78.     frame.setBackground(Color.lightGray);
  79.  
  80.     /* Create the JTreeModel. */
  81.     DefaultMutableTreeNode root = createNewNode("Root");
  82.     treeModel = new SampleTreeModel(root);
  83.  
  84.     /* Create the tree. */
  85.     tree = new JTree(treeModel);
  86.  
  87.     /* Enable tool tips for the tree, without this tool tips will not
  88.        be picked up. */
  89.     ToolTipManager.sharedInstance().registerComponent(tree);
  90.  
  91.     /* Make the tree use an instance of SampleTreeCellRenderer for
  92.        drawing. */
  93.     tree.setCellRenderer(new SampleTreeCellRenderer());
  94.  
  95.     /* Make tree ask for the height of each row. */
  96.     tree.setRowHeight(-1);
  97.  
  98.     /* Put the Tree in a scroller. */
  99.     JScrollPane        sp = new JScrollPane();
  100.     sp.setPreferredSize(new Dimension(300, 300));
  101.     sp.getViewport().add(tree);
  102.  
  103.     /* And show it. */
  104.     panel.setLayout(new BorderLayout());
  105.     panel.add("Center", sp);
  106.     panel.add("South", constructOptionsPanel());
  107.  
  108.     frame.addWindowListener( new WindowAdapter() {
  109.         public void windowClosing(WindowEvent e) {System.exit(0);}});
  110.  
  111.     frame.pack();
  112.     frame.show();
  113.     }
  114.  
  115.     /** Constructs a JPanel containing check boxes for the different
  116.       * options that tree supports. */
  117.     private JPanel constructOptionsPanel() {
  118.     JCheckBox               aCheckbox;
  119.     JPanel           retPanel = new JPanel(false);
  120.     JPanel           borderPane = new JPanel(false);
  121.  
  122.     borderPane.setLayout(new BorderLayout());
  123.     retPanel.setLayout(new FlowLayout());
  124.  
  125.     aCheckbox = new JCheckBox("show handles");
  126.     aCheckbox.setSelected(tree.getShowsRootHandles());
  127.     aCheckbox.addChangeListener(new ShowHandlesChangeListener());
  128.     retPanel.add(aCheckbox);
  129.  
  130.     aCheckbox = new JCheckBox("show root");
  131.     aCheckbox.setSelected(tree.isRootVisible());
  132.     aCheckbox.addChangeListener(new ShowRootChangeListener());
  133.     retPanel.add(aCheckbox);
  134.  
  135.     aCheckbox = new JCheckBox("editable");
  136.     aCheckbox.setSelected(tree.isEditable());
  137.     aCheckbox.addChangeListener(new TreeEditableChangeListener());
  138.     aCheckbox.setToolTipText("Triple click to edit");
  139.     retPanel.add(aCheckbox);
  140.  
  141.     borderPane.add(retPanel, BorderLayout.CENTER);
  142.  
  143.     /* Create a set of radio buttons that dictate what selection should
  144.        be allowed in the tree. */
  145.     ButtonGroup           group = new ButtonGroup();
  146.     JPanel         buttonPane = new JPanel(false);
  147.     JRadioButton          button;
  148.  
  149.     buttonPane.setLayout(new FlowLayout());
  150.     button = new JRadioButton("Single");
  151.     button.addActionListener(new AbstractAction() {
  152.         public boolean isEnabled() { return true; }
  153.         public void actionPerformed(ActionEvent e) {
  154.         tree.getSelectionModel().setSelectionMode
  155.             (TreeSelectionModel.SINGLE_TREE_SELECTION);
  156.         }
  157.     });
  158.     group.add(button);
  159.     buttonPane.add(button);
  160.     button = new JRadioButton("Contiguous");
  161.     button.addActionListener(new AbstractAction() {
  162.         public boolean isEnabled() { return true; }
  163.         public void actionPerformed(ActionEvent e) {
  164.         tree.getSelectionModel().setSelectionMode
  165.             (TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
  166.         }
  167.     });
  168.     group.add(button);
  169.     buttonPane.add(button);
  170.     button = new JRadioButton("Discontiguous");
  171.     button.addActionListener(new AbstractAction() {
  172.         public boolean isEnabled() { return true; }
  173.         public void actionPerformed(ActionEvent e) {
  174.         tree.getSelectionModel().setSelectionMode
  175.             (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
  176.         }
  177.     });
  178.     button.setSelected(true);
  179.     group.add(button);
  180.     buttonPane.add(button);
  181.  
  182.     borderPane.add(buttonPane, BorderLayout.SOUTH);
  183.  
  184.     // NOTE: This will be enabled in a future release.
  185.     // Create a label and combobox to determine how many clicks are
  186.     // needed to expand.
  187. /*
  188.     JPanel               clickPanel = new JPanel();
  189.     Object[]             values = { "Never", new Integer(1),
  190.                     new Integer(2), new Integer(3) };
  191.     final JComboBox      clickCBox = new JComboBox(values);
  192.  
  193.     clickPanel.setLayout(new FlowLayout());
  194.     clickPanel.add(new JLabel("Click count to expand:"));
  195.     clickCBox.setSelectedIndex(2);
  196.     clickCBox.addActionListener(new ActionListener() {
  197.         public void actionPerformed(ActionEvent ae) {
  198.         Object       selItem = clickCBox.getSelectedItem();
  199.  
  200.         if(selItem instanceof Integer)
  201.             tree.setToggleClickCount(((Integer)selItem).intValue());
  202.         else // Don't toggle
  203.             tree.setToggleClickCount(0);
  204.         }
  205.     });
  206.     clickPanel.add(clickCBox);
  207.     borderPane.add(clickPanel, BorderLayout.NORTH);
  208. */
  209.     return borderPane;
  210.     }
  211.  
  212.     /** Construct a menu. */
  213.     private JMenuBar constructMenuBar() {
  214.     JMenu            menu;
  215.     JMenuBar         menuBar = new JMenuBar();
  216.     JMenuItem        menuItem;
  217.  
  218.     /* Good ol exit. */
  219.     menu = new JMenu("File");
  220.     menuBar.add(menu);
  221.  
  222.     menuItem = menu.add(new JMenuItem("Exit"));
  223.     menuItem.addActionListener(new ActionListener() {
  224.         public void actionPerformed(ActionEvent e) {
  225.         System.exit(0);
  226.         }});
  227.  
  228.     /* Tree related stuff. */
  229.     menu = new JMenu("Tree");
  230.     menuBar.add(menu);
  231.  
  232.     menuItem = menu.add(new JMenuItem("Add"));
  233.     menuItem.addActionListener(new AddAction());
  234.  
  235.     menuItem = menu.add(new JMenuItem("Insert"));
  236.     menuItem.addActionListener(new InsertAction());
  237.  
  238.     menuItem = menu.add(new JMenuItem("Reload"));
  239.     menuItem.addActionListener(new ReloadAction());
  240.  
  241.     menuItem = menu.add(new JMenuItem("Remove"));
  242.     menuItem.addActionListener(new RemoveAction());
  243.  
  244.     return menuBar;
  245.     }
  246.  
  247.     /**
  248.       * Returns the TreeNode instance that is selected in the tree.
  249.       * If nothing is selected, null is returned.
  250.       */
  251.     protected DefaultMutableTreeNode getSelectedNode() {
  252.     TreePath   selPath = tree.getSelectionPath();
  253.  
  254.     if(selPath != null)
  255.         return (DefaultMutableTreeNode)selPath.getLastPathComponent();
  256.     return null;
  257.     }
  258.  
  259.     protected DefaultMutableTreeNode createNewNode(String name) {
  260.     return new DynamicTreeNode(new SampleData(null, Color.black, name));
  261.     }
  262.  
  263.     /**
  264.       * AddAction is used to add a new item after the selected item.
  265.       */
  266.     class AddAction extends Object implements ActionListener
  267.     {
  268.     /** Number of nodes that have been added. */
  269.     public int               addCount;
  270.  
  271.     /**
  272.       * Messaged when the user clicks on the Add menu item.
  273.       * Determines the selection from the Tree and adds an item
  274.       * after that.  If nothing is selected, an item is added to
  275.       * the root.
  276.       */
  277.     public void actionPerformed(ActionEvent e) {
  278.         int               newIndex;
  279.         DefaultMutableTreeNode          lastItem = getSelectedNode();
  280.         DefaultMutableTreeNode          parent;
  281.  
  282.         /* Determine where to create the new node. */
  283.         if(lastItem != null) {
  284.         parent = (DefaultMutableTreeNode)lastItem.getParent();
  285.         if(parent == null) {
  286.             parent = (DefaultMutableTreeNode)treeModel.getRoot();
  287.             lastItem = null;
  288.         }
  289.         }
  290.         else
  291.         parent = (DefaultMutableTreeNode)treeModel.getRoot();
  292.         if(lastItem == null)
  293.         newIndex = treeModel.getChildCount(parent);
  294.         else
  295.         newIndex = parent.getIndex(lastItem) + 1;
  296.  
  297.         /* Let the treemodel know. */
  298.         treeModel.insertNodeInto(createNewNode("Added " +
  299.                     Integer.toString(addCount++)),
  300.                      parent, newIndex);
  301.     }
  302.     } // End of SampleTree.AddAction
  303.  
  304.  
  305.     /**
  306.       * InsertAction is used to insert a new item before the selected item.
  307.       */
  308.     class InsertAction extends Object implements ActionListener
  309.     {
  310.     /** Number of nodes that have been added. */
  311.     public int               insertCount;
  312.  
  313.     /**
  314.       * Messaged when the user clicks on the Insert menu item.
  315.       * Determines the selection from the Tree and inserts an item
  316.       * after that.  If nothing is selected, an item is added to
  317.       * the root.
  318.       */
  319.     public void actionPerformed(ActionEvent e) {
  320.         int               newIndex;
  321.         DefaultMutableTreeNode          lastItem = getSelectedNode();
  322.         DefaultMutableTreeNode          parent;
  323.  
  324.         /* Determine where to create the new node. */
  325.         if(lastItem != null) {
  326.         parent = (DefaultMutableTreeNode)lastItem.getParent();
  327.         if(parent == null) {
  328.             parent = (DefaultMutableTreeNode)treeModel.getRoot();
  329.             lastItem = null;
  330.         }
  331.         }
  332.         else
  333.         parent = (DefaultMutableTreeNode)treeModel.getRoot();
  334.         if(lastItem == null)
  335.         newIndex = treeModel.getChildCount(parent);
  336.         else
  337.         newIndex = parent.getIndex(lastItem);
  338.  
  339.         /* Let the treemodel know. */
  340.         treeModel.insertNodeInto(createNewNode("Inserted " +
  341.                     Integer.toString(insertCount++)),
  342.                      parent, newIndex);
  343.     }
  344.     } // End of SampleTree.InsertAction
  345.  
  346.  
  347.     /**
  348.       * ReloadAction is used to reload from the selected node.  If nothing
  349.       * is selected, reload is not issued.
  350.       */
  351.     class ReloadAction extends Object implements ActionListener
  352.     {
  353.     /**
  354.       * Messaged when the user clicks on the Reload menu item.
  355.       * Determines the selection from the Tree and asks the treemodel
  356.       * to reload from that node.
  357.       */
  358.     public void actionPerformed(ActionEvent e) {
  359.         DefaultMutableTreeNode          lastItem = getSelectedNode();
  360.  
  361.         if(lastItem != null)
  362.         treeModel.reload(lastItem);
  363.     }
  364.     } // End of SampleTree.ReloadAction
  365.  
  366.     /**
  367.       * RemoveAction removes the selected node from the tree.  If
  368.       * The root or nothing is selected nothing is removed.
  369.       */
  370.     class RemoveAction extends Object implements ActionListener
  371.     {
  372.     /**
  373.       * Removes the selected item as long as it isn't root.
  374.       */
  375.     public void actionPerformed(ActionEvent e) {
  376.         DefaultMutableTreeNode          lastItem = getSelectedNode();
  377.  
  378.         if(lastItem != null && lastItem != (DefaultMutableTreeNode)treeModel.getRoot()) {
  379.         treeModel.removeNodeFromParent(lastItem);
  380.         }
  381.     }
  382.     } // End of SampleTree.RemoveAction
  383.  
  384.  
  385.     /**
  386.       * ShowHandlesChangeListener implements the ChangeListener interface
  387.       * to toggle the state of showing the handles in the tree.
  388.       */
  389.     class ShowHandlesChangeListener extends Object implements ChangeListener
  390.     {
  391.     public void stateChanged(ChangeEvent e) {
  392.         tree.setShowsRootHandles(((JCheckBox)e.getSource()).isSelected());
  393.     }
  394.  
  395.     } // End of class SampleTree.ShowHandlesChangeListener
  396.  
  397.  
  398.     /**
  399.       * ShowRootChangeListener implements the ChangeListener interface
  400.       * to toggle the state of showing the root node in the tree.
  401.       */
  402.     class ShowRootChangeListener extends Object implements ChangeListener
  403.     {
  404.     public void stateChanged(ChangeEvent e) {
  405.         tree.setRootVisible(((JCheckBox)e.getSource()).isSelected());
  406.     }
  407.  
  408.     } // End of class SampleTree.ShowRootChangeListener
  409.  
  410.  
  411.     /**
  412.       * TreeEditableChangeListener implements the ChangeListener interface
  413.       * to toggle between allowing editing and now allowing editing in
  414.       * the tree.
  415.       */
  416.     class TreeEditableChangeListener extends Object implements ChangeListener
  417.     {
  418.     public void stateChanged(ChangeEvent e) {
  419.         tree.setEditable(((JCheckBox)e.getSource()).isSelected());
  420.     }
  421.  
  422.     } // End of class SampleTree.TreeEditableChangeListener
  423.  
  424.  
  425.     static public void main(String args[]) {
  426.     new SampleTree();
  427.     }
  428.  
  429. }
  430.